package com.bop.dehong.decaifu;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.DeviceUuidFactory;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.StringUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.base.TopManager;
import com.bop.dehong.bid.MyBidActivity;
import com.bop.dehong.center.RechargeActivity;
import com.bop.dehong.config.Config;
import com.bop.dehong.info.entity.ToubiaoEntity;
import com.bop.dehong.info.entity.ToubiaoItemEntity;
import com.bop.dehong.info.entity.ToubiaoShouyiEntity;
import com.bop.dehong.info.entity.UserEntity;
import com.bop.dehong.http.model.GetUserInfoModel;
import com.bop.dehong.http.model.TiyanjinBidModel;
import com.bop.dehong.http.model.ToubiaoModel;
import com.bop.dehong.http.model.ToubiaoshouyiModel;
import com.bop.dehong.info.EmptyInfo;
import com.bop.dehong.info.UserInfo;
import com.bop.dehong.login.LoginActivity;
import com.bop.dehong.setting.NameAuthActivity;
import com.bop.dehong.util.CodeUtil;
import com.bop.dehong.widget.RoundProgressBar;

public class ToubiaoTyjActivity extends BaseActivity {
	private ToubiaoModel toubiaoModel;
	private ToubiaoshouyiModel toubiaoshouyiModel;
	private TiyanjinBidModel tiyanjinBidModel;
	private String id;
	private String uid, price;
	private TextView toubiao_rate, toubiao_money, toubiao_time;
	private RoundProgressBar toubiao_count;
	private TextView toubiao_annual_revenue;
	private TextView toubiao_btn;
	private EditText toubiao_avaliblemoney; 
	private Float avaliblemoney = 0.0f, surplus = 0.0f/*, rate*/;
	private int min;
	private LinearLayout mViewLayout;
	private String tip;
	private Dialog toubiaoDialog; 
	private Dialog mBidDialog;
	private TextView tipTv;
	private EditText mEdtCode;
	private ImageView mBtnCode;
	private String getCode;
	private int emoney;
	private TopManager manager;
	private GetUserInfoModel mGetInfoModel;
	private Long local;
	private CodeUtil util;
	
	@Override
	protected void initTop() {
		View mView = getView(R.id.toubiao_top);
		manager = new TopManager(mView);
		manager.setLeftImageVisibility(View.VISIBLE);
		manager.setRightTextVisibility(View.VISIBLE);
		manager.setRightText("详情");
		manager.setRightTextOnClick(this);
	}
	
	@Override
	protected void initUI() {
		id = getIntent().getExtras().getString(Config.CAT_ID);
		if (DeHongApp.mLoginEntity != null) {
			uid = DeHongApp.mLoginEntity.getUid();
		}else {
			uid = "";
		}
		mViewLayout = getView(R.id.view_layout);
		toubiao_rate = getView(R.id.toubiao_rate);
		toubiao_money = getView(R.id.toubiao_money);
		toubiao_time = getView(R.id.toubiao_time);
		toubiao_count = getView(R.id.toubiao_count_roundprobar);
		toubiao_avaliblemoney = getView(R.id.toubiao_avaliblemoney);
		toubiao_annual_revenue = getView(R.id.toubiao_annual_revenue);
		toubiao_btn = getView(R.id.toubiao_btn);
		registerOnClickListener(toubiao_btn,mViewLayout);
		toubiao_avaliblemoney.setOnFocusChangeListener(new android.view.View.
				OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				price = getStr4TextView(toubiao_avaliblemoney); 
				if (StringUtils.isNotEmpty(price) && !hasFocus && !toubiao_btn.hasFocus()) {
					     // 此处为失去焦点时的处理内容
				         getShouyi();	
					}
				}
		});
	}
	 /**
	 * 提示
	 */
	 @SuppressLint("NewApi")
	 private void showDialog(String msg){ 
	    	toubiaoDialog = new Dialog(this, R.style.MyDialogStyle);
			View view = View.inflate(this, R.layout.dialog_re_login, null);
			toubiaoDialog.setContentView(view);
			toubiaoDialog.setCancelable(false);
			TextView msgtv = getView(view, R.id.textView2);
			msgtv.setText(msg);
			Button loginBtn = getView(view, R.id.re_login);
			loginBtn.setText("确定");
			registerOnClickListener(loginBtn);
			toubiaoDialog.show();
	  }  
	
	 
	    /**
		 * 投标
		 */
		private void getBidDialog() {
			mBidDialog = new Dialog(this, R.style.MyDialogStyle);
			View view = View.inflate(this, R.layout.dialog_tyjbid_layout, null);
			TextView titleTv = getView(view, R.id.title);
			tipTv = getView(view, R.id.message);
			mEdtCode = getView(view, R.id.bid_code);
			mBtnCode = getView(view, R.id.bid_btn_code); 
			util = CodeUtil.getInstance();
			mBtnCode.setImageBitmap(util.getBitmap());
			getCode = util.getCode(); //获取显示的验证码
			
			titleTv.setText("你确定要投标吗？");
			Button sureBtn = getView(view, R.id.btn_sure);
			getView(view, R.id.btn_cancel).setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) 
				{
					mBidDialog.dismiss();
				}
			});
			mBidDialog.setContentView(view);
			registerOnClickListener(sureBtn, mBtnCode);
			mBidDialog.show();
		}
		
		
		RequestCallBack<EmptyInfo> callback2 = new RequestCallBack<EmptyInfo>() {

			@Override
			public void end() {
				disappearProgressDialog();
			}

			@Override
			public void onSuccess(EmptyInfo info) {
				super.onSuccess(info);
				ToastUtils.show(ToubiaoTyjActivity.this, "投标成功");
				reqInfo();
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						openActivity(MyBidActivity.class);
					}
				}, 1000);
			}
			
		};
		
	    
	    /**
	     * 判断投标金额
	     */
	    private boolean judge() {
	    	if (TextUtils.isEmpty(price)) {
	 			ToastUtils.show(ToubiaoTyjActivity.this, "请输入金额");
	 			return false;
	 		}else {
	 			Float investmoney =  Float.parseFloat(price);
		        if (investmoney > surplus) {
					showDialog("投标金额不能大于可投金额,请重新输入！");
			        return false;
				}
		        if (investmoney < min || investmoney <= 0) {
					showDialog("投标金额必须大于最小投标额" + min + "！");
			        return false;
				}
		        if (investmoney % min != 0) {
		        	showDialog("投标金额为最小投标额" + min + "的整数倍数,请重新输入!");  
			        return false;
				}
			}
	    	return true;
		}
	    

	
	@Override
	protected void initData() {
		showProgressDialog();
		if (toubiaoModel == null) {
			toubiaoModel = new ToubiaoModel(this, callback);
		}
		toubiaoModel.doNet(id, uid);
	}

	RequestCallBack<ToubiaoEntity> callback = new RequestCallBack<ToubiaoEntity>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}
		
		public void onSuccess(ToubiaoEntity info) {
			super.onSuccess(info);
			ToubiaoItemEntity item = info.getList().getItem();
			manager.setTitle(item.getTitle());
			toubiao_rate.setText(item.getRates());
			toubiao_money.setText(item.getMoney());
			toubiao_time.setText(item.getDeadlines());
			
			toubiao_count.setProgress(item.getPercent());
			toubiao_count.setTitleName("人购买");
			toubiao_count.setCount(info.getList().getCount());
			tip = info.getList().getTips();//新用户必须先投个其他标才可以投体验标
			if (StringUtils.isNotEmpty(tip))
			{
				cannotBit();
			}
			emoney = info.getList().getEmoney();
			toubiao_avaliblemoney.setHint("可使用体验金： " + emoney);
			avaliblemoney = Float.valueOf(emoney);	
//			rate = Float.valueOf(item.getRates()) / 100;
			if (StringUtils.isNotEmpty(item.getSurplus())) {
				surplus = Float.valueOf(item.getSurplus());	
			}
			min = Integer.valueOf(item.getMin());
		};
		
	};
	
	/*
	 * 计算收益
	 */
	private void getShouyi() {
		showProgressDialog();
		if (toubiaoshouyiModel == null) {
			toubiaoshouyiModel = new ToubiaoshouyiModel(this, callback1);
		}
		toubiaoshouyiModel.doNet(id, uid, price, "");
//		mMoneyChanged = false;
	}
	
	RequestCallBack<ToubiaoShouyiEntity> callback1 = new RequestCallBack<ToubiaoShouyiEntity>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(ToubiaoShouyiEntity info) {
			super.onSuccess(info);
			toubiao_annual_revenue.setText(StringUtils.getFormatValue(info.getInterest()));
		}
		
	};
	
	/*
	 * 不能投标时可以点击弹出提示语
	 */
	@SuppressLint("NewApi")
	private void cannotBit() {
		toubiao_btn.setBackground(getResources().getDrawable(R.drawable.bg_btn_grey));
		toubiao_avaliblemoney.setFocusable(false);
//		toubiao_btn.setClickable(false);
	}
	
	@Override
	protected int getContentViewId() {
		TAG = getClass().getName();
		return R.layout.activity_toubiaotyj;
	}	
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (toubiaoDialog != null) {
    		toubiaoDialog.dismiss();
    		toubiaoDialog = null;
		}
		if (mBidDialog != null) {
			mBidDialog.dismiss();
			mBidDialog = null;
		}
	}
	
	private void reqInfo(){
		showProgressDialog();
		if (mGetInfoModel == null) {
			mGetInfoModel = new GetUserInfoModel(this, getCallback);
		}
		local = System.currentTimeMillis() / 1000;
		mGetInfoModel.doNet(DeHongApp.mLoginEntity.uid);
	}
	
	RequestCallBack<UserInfo> getCallback = new RequestCallBack<UserInfo>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(UserInfo info) {
			super.onSuccess(info);
			Long net = info.stamp;
			Long modify = net - local;
			if (Math.abs(modify) >= 300) {
				PreferencesUtils.putLong(ToubiaoTyjActivity.this, Config.TAG, modify);	
			}
			DeHongApp.mUserInfo = info;
			String emoney = DeHongApp.mUserInfo.emoney.emoney;
			if (StringUtils.isNotEmpty(emoney))
			{
				avaliblemoney = Float.valueOf(emoney);//可投体验金
			}
		}
		
	};
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (requestCode == 100) {
			if (DeHongApp.mLoginEntity != null) {
				uid = DeHongApp.mLoginEntity.getUid();
			}else {
				uid = "";
			}
		}else
		if (requestCode == 101 || requestCode == 103) {
			reqInfo();
		}		 
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.bid_btn_code:
			util = CodeUtil.getInstance();
			mBtnCode.setImageBitmap(util.getBitmap());
			getCode = util.getCode();
			break;
		case R.id.top_bar_right_txt:
			Bundle bundle = new Bundle();
			bundle.putString(Config.CAT_ID, id);
			openActivity(DeCaifuActivity.class, bundle);	
			break;

		case R.id.toubiao_btn:
			price = getStr4TextView(toubiao_avaliblemoney);
			if (StringUtils.isNotEmpty(uid)) {
				int mCertification = Integer.valueOf(DeHongApp.mLoginEntity.certification);
				if (mCertification == 2)
				{
					if (StringUtils.isNotEmpty(tip)) {	
						showDialog(tip);
						return;
					}
					if (!judge()) {
						return;
					};     
					Float investmoney = Float.parseFloat(price);
					if (investmoney > avaliblemoney) 
					{
					    ToastUtils.showLong(this, "投标金额不能大于可用体验金，请重新输入！"); 
//						Intent intent = new Intent(ToubiaoTyjActivity.this, RechargeActivity.class);
//						startActivityForResult(intent, 103);
					    return;
					 } 
					 getBidDialog();
					}else if (mCertification == 0){
						ToastUtils.showLong(this, "你还未实名认证，请先实名认证再投标！");
						Intent intent3 = new Intent(ToubiaoTyjActivity.this, NameAuthActivity.class);
						intent3.putExtra(Config.UID, uid);
						startActivityForResult(intent3, 101);
						return;
					}else {
						showDialog("实名认证中，请等待！");
				}
			}else {
				ToastUtils.showLong(this, "你还未登录，请先登录再投标！");
				Intent intent = new Intent(ToubiaoTyjActivity.this, LoginActivity.class);
				intent.putExtra(Config.GO_BACK, true);
				startActivityForResult(intent, 100);
				return;
			}
			
			break;
		case R.id.view_layout:
			toubiao_avaliblemoney.clearFocus();
			break;
		case R.id.re_login:
			if (toubiaoDialog != null) {
	    		toubiaoDialog.dismiss();
	    		toubiaoDialog = null;
			}
			break;
		case R.id.btn_sure:
			String v_code = getStr4TextView(mEdtCode);
			if(v_code == null || v_code.equals("")){
				tipTv.setVisibility(View.VISIBLE);
				tipTv.setText("没有填写验证码");
				return;
			}
			if (v_code.length() != 4) {
				tipTv.setVisibility(View.VISIBLE);
				tipTv.setText("验证码位数不对");
				return;
			}
			if(!v_code.equalsIgnoreCase(getCode)){
				tipTv.setVisibility(View.VISIBLE);
				tipTv.setText("验证码填写不正确");
				return;
			}
			mBidDialog.dismiss();
			String phonetype = "";
			DeviceUuidFactory factory = new DeviceUuidFactory(ToubiaoTyjActivity.this);
			phonetype = factory.getPhoneType();
			if (tiyanjinBidModel == null) {
				tiyanjinBidModel = new TiyanjinBidModel(ToubiaoTyjActivity.this, callback2);
			}
			tiyanjinBidModel.doNet(DeHongApp.mLoginEntity.uid, id, price, phonetype);
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
}
